package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.model.vo.system.SysMenuVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper ;
    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {
//        1.获取输入验证码和存储到redis的key名称 
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
//        2.根据获取的redis的key，查询redis里面存储的验证码
//        todo 验证码过期如何判断
        String redisCode = redisTemplate.opsForValue().get("user:validate" + codeKey);
//        System.out.println("code:" + redisCode);
//        3.比较输入的验证码和redis存储验证码是否一致
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
//        4.如果不一致提示校验失败
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
//        5.如果一致，删除redis里面的验证码
        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey);
//        根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(loginDto.getUserName());
        if (sysUser == null) {
//            throw new RuntimeException("用户名或者密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
//        验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if (!md5InputPassword.equals(sysUser.getPassword())) {
//            throw new RuntimeException("用户名或者密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
//        登录成功，生成用户唯一标识token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
//        把登录成功的用户信息放到redis
        redisTemplate.opsForValue()
                .set("user:login" + token,
                        JSON.toJSONString(sysUser),
                        7,
                        TimeUnit.DAYS);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
//        1.校验token是否正确
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        System.out.println("user:" + sysUser);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
//        先查询用户是否存在
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(sysUser.getUserName());
        if(dbSysUser!=null){
//        如果存在抛出用户名已存在异常
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
//        对密码进行加密 这一步应该在客户端请求时就是加密的吧？
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(1);
        sysUserMapper.save(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
       sysUserMapper.update(sysUser);
    }

    @Override
    public void deleteById(Long roleId) {
        sysUserMapper.deleteById(roleId);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 删除之前的用户所对应的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId()) ;

        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId->{
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        });
    }
}
